package com.fuego.creditsystemuser.controller;


import com.fuego.creditsystemuser.service.IUserInfoService;
import com.fuego.creditsystemuser.service.IUserService;
import jakarta.servlet.http.HttpServletRequest;
import org.example.dto.Result;
import org.example.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/user-info")
public class UserInfoController {

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IUserService userService;

    @GetMapping("/status")
    public Result getVerificationStatus(HttpServletRequest request) {
        Long userId = userService.getIdByToken(request);
        if (userId == null) {
            return Result.fail("用户未登录");
        }
        UserInfo userInfo = userInfoService.getById(userId);
        if (userInfo != null) {
            return Result.ok(userInfo);
        }
        return Result.fail("未实名认证");
    }

    @PostMapping
    public Result verifyIdentity(@RequestBody UserInfo userInfo,HttpServletRequest request) {
        Long userId = userService.getIdByToken(request);
        if (userId == null) {
            return Result.fail("用户未登录");
        }

        // 检查是否已认证
        if (userInfoService.getById(userId) != null) {
            return Result.fail("用户已实名认证，无法重复认证");
        }

        // 验证输入
        if (!isValidIdNumber(userInfo.getIdNumber())) {
            return Result.fail("无效的身份证号");
        }
        if (userInfo.getRealName() == null || userInfo.getRealName().length() < 2 || userInfo.getRealName().length() > 10) {
            return Result.fail("姓名长度必须在2到10个字符");
        }

        userInfo.setUserId(userId);
        userInfo.setCreateTime(LocalDateTime.now());

        boolean saved = userInfoService.save(userInfo);
        return saved ? Result.ok() : Result.fail("实名认证失败");
    }



    private boolean isValidIdNumber(String idNumber) {
        if (idNumber == null) return false;
        return idNumber.matches("^\\d{17}(\\d|X|x)$");
    }
}